#!/usr/bin/env python -OO
# -*- coding: utf-8 -*-

# Copyright © 2008,2009 Trust Digital Technology Laboratory, Shanghai Jiao Tong University.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author:
#   XING Dong sheng <homer.xing@gmail.com>

from __future__ import with_statement

__all__ = ['installwar3']

import os, sys, re
import xdg.DesktopEntry
from softwaredependent import *
from softwareindependent import TempOwn
from installcommonuse import installwine

def war3regfile():
	execute('cp %s ~/.wine/drive_c/'%(FILES+'war3.reg') )
	execute(r"wine regedit c:\\war3.reg")

def war3icon():
	execute("rm -f '"+DESKTOP+"Frozen Throne.desktop'")
	execute("rm -f '"+DESKTOP+"Frozen Throne.lnk'")
	execute("rm -f %s/ORPG*"%DESKTOP)
	fn = "War3.desktop"
	e = xdg.DesktopEntry.DesktopEntry( os.path.abspath(fn) )
	e.set('Version','1.0')
	e.set('Encoding','UTF-8')
	e.set('Name','WarcraftIII')
	e.set('Exec','wine "C:\\Program Files\\Warcraft III\\Frozen Throne.exe" -opengl')
	e.set('Type','Application')
	e.set('StartupWMClass','Wine')
	e.set('Path','%s/.wine/dosdevices/c:/Program Files/Warcraft III'%HOME)
	e.set('Icon','625a_frozen throne.0')
	e.set('Categories','Game;')
	e.write()
	execute("sudo mv War3.desktop /usr/share/applications/")

def downloadwar3():
	os.system("mkdir %s/War3" % LOCAL )
	download("war3roc")
	download("war3tft")
	download("war3dota")
	download("war3patch")
	download("war3bn")
	download("war3l")
	#自动点击按钮和填写文字的程序
	auto1=download("war3auto1")
	auto2=download("war3auto2")
	auto3=download("war3auto3")
	return auto1, auto2, auto3

def roc():
	os.system("sudo mkdir /mnt/war3")
	src = LOCAL+softwarelist["war3roc"]
	execute("sudo mount -t iso9660 -o iocharset=utf8,loop %s /mnt/war3" % src )
	if execute("wine %s &"%auto1):
		return execute("wine '/mnt/war3/Reign of Chaos/install.exe' >/dev/null 2>/dev/null")
	return False

def tft():
	os.system("sudo mkdir /mnt/war3tft")
	src = LOCAL+softwarelist["war3tft"]
	if execute("sudo mount -t iso9660 -o iocharset=utf8,loop %s /mnt/war3tft" % src ):
		if execute("wine %s &"%auto2):
			if execute("wine '/mnt/war3tft/Frozen Throne/install.exe' >/dev/null 2>/dev/null"):
				return True
	return False

def patch():
	if execute("mv %s%s %s" %(LOCAL, softwarelist["war3patch"], WINEROOT) ):
		execute("wine %s &"%auto3)
		if execute(r"wine c:\\%s 2>/dev/null"%softwarelist["war3patch"][4:]):
			return True
	return False

def dota():
	#DotA
	src = LOCAL+softwarelist["war3dota"]
	dest = WINEROOT +"Program Files/Warcraft III/Maps/FrozenThrone/Scenario/"
	return execute("mkdir -p '%s'"%dest) and execute("cp %s '%s' "%(src, dest) )

def bn():
	#登录交大BN的工具
	src = LOCAL+softwarelist["war3bn"]
	dest = WINEROOT +"Program Files/Warcraft III/"
	if execute("cp %s '%s' "%(src, dest) ):
		src = LOCAL+softwarelist["war3l"]
		return execute("cp %s '%s' "%(src, dest) ) and execute("cd '%s' && unzip -o w3l.zip"%dest )
	return False

def removelnk():
	#FIXME 令这些命令更加精确
	execute("rm %s/桌面/*.lnk -f"%HOME)
	execute("rm %s/*.lnk -f"%HOME)

def screensize():
	p=os.popen('xdpyinfo -display :0.0 | grep dimensions')
	line=p.readline()
	p.close()
	p=re.compile(r'\D*([0-9]+)x([0-9]+)\D*')
	m=p.match(line)
	if m!=None:
		width=int( m.group(1) )
		height=int( m.group(2) )
		f=open( os.path.expanduser('~/.wine/drive_c/war3res.reg'), 'w' )
		f.write(r'''REGEDIT4

[HKEY_CURRENT_USER\Software\Blizzard Entertainment\Warcraft III\Video]
resheight=dword:%08x
reswidth=dword:%08x
'''%(height,width) )
		f.close()
		os.system('wine regedit ~/.wine/drive_c/war3res.reg')

def installwar3():
	global auto1, auto2, auto3
	installwine()
	auto1, auto2, auto3 = downloadwar3()
	war3regfile()
	roc()
	tft()
	dota()
	bn()
	war3icon()
	removelnk()
	screensize()
	patch()

if __name__ == "__main__":
	installwar3()
